package cn.wanda.bi.sunshine.platform.server.controller;

import cn.wanda.bi.sunshine.platform.server.bean.model.City;
import cn.wanda.bi.sunshine.platform.server.client.response.elasticsearch.UserLabelBean;
import cn.wanda.bi.sunshine.platform.server.client.response.elasticsearch.UserLabelBucket;
import cn.wanda.bi.sunshine.platform.server.controller.request.LabelQueryRequest;
import cn.wanda.bi.sunshine.platform.server.controller.response.CityResponse;
import cn.wanda.bi.sunshine.platform.server.controller.response.common.SimpleResponse;
import cn.wanda.bi.sunshine.platform.server.service.CityService;
import cn.wanda.bi.sunshine.platform.server.service.LabelDictionaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by James on 17/7/26.
 */
@Api(description = "城市服务")
@RestController
@RequestMapping(value = "/v1/label", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DMPCityController {

    public static final Logger logger = LoggerFactory.getLogger(DMPCityController.class);

    @Autowired
    private CityService cityService;
    @Autowired
    private LabelDictionaryService labelDictionaryService;

    @ApiOperation("查询城市列表数据,传入参数是查询条件组成的列表，应用的appid和secret，输出是符合条件的所有城市列表详情")
    @RequestMapping(value = "/city", method = RequestMethod.POST)
    public SimpleResponse queryCity(
    		@ApiParam(value = "查询条件") @RequestBody LabelQueryRequest request,
            @RequestHeader(value = "appid", defaultValue = "ss8f239bb5b209c060") String appid,
            @RequestHeader(value = "secret", defaultValue = "eaf109772eec37a5663b6659fbe5c56a") String secret
    ) {
    	UserLabelBean userLabelBean = labelDictionaryService.QueryUserValue("city_name",request);
        List<UserLabelBucket> buckets = userLabelBean.getAggregations().getDistinct_w().getBuckets();
        List<CityResponse> cities = new ArrayList<>();
        buckets.forEach(p -> {
            City ret = cityService.querySingle(p.getKey());
            if (null != ret) {
                CityResponse city = new CityResponse();
                city.setTotal(p.getDoc_count());
                city.setCity(ret);
                cities.add(city);
            }
        });
        return SimpleResponse.success(cities);
    }

}
